<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item
          v-for="(item, index) in breadList"
          :key="index"
          :to="{ path: item.path }"
        >
          {{ item.meta.title }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-select
          v-model="query.category"
          placeholder="景点等级"
          class="handle-select mr10"
        >
          <el-option key="5" label="全部" value=""></el-option>
          <el-option key="0" label="5A" value="0"></el-option>
          <el-option key="1" label="4A" value="1"></el-option>
          <el-option key="2" label="3A" value="2"></el-option>
          <el-option key="3" label="2A" value="3"></el-option>
          <el-option key="4" label="1A" value="4"></el-option>
        </el-select>
        <el-input
          v-model="query.name"
          placeholder="请输入景点名"
          class="handle-input mr10"
        ></el-input>
        <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
      </div>
      <el-table
        :data="tableData"
        border
        stripe
        size="large"
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
      >
        <el-table-column
          prop="travelId"
          label="ID"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column label="logo" width="150" align="center" prop="logo">
          <template #default="scope">
            <img :src="`${IMG_URL}${scope.row.logo}`" width="80" height="80" />
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="景点名"
          width="80"
          align="center"
        ></el-table-column>
        <el-table-column label="景点类型" width="110" align="center">
          <template #default="scope">
            <el-tag
              :type="
                scope.row.category == '0'
                  ? 'danger'
                  : scope.row.category == '1'
                  ? 'warning'
                  : scope.row.category == '2'
                  ? 'success'
                  : scope.row.category == '3'
                  ? 'Brand Color'
                  : scope.row.category == '4'
                  ? 'info'
                  : 'Extra-light Border'
              "
            >
              {{
                scope.row.category == "0"
                  ? "5A"
                  : scope.row.category == "1"
                  ? "4A"
                  : scope.row.category == "2"
                  ? "3A"
                  : scope.row.category == "3"
                  ? "2A"
                  : "1A"
              }}
            </el-tag>
          </template>
        </el-table-column>    
        <el-table-column
          prop="updatedAt"
          label="修改时间"
          width="200"
          align="center"
          :formatter="formatDate"
        ></el-table-column>
        <el-table-column
          prop="desc"
          label="简介"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              link
              :icon="EditPen"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >

            <el-popconfirm
              title="确定要删除此景点？"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="handleDelete(scope.$index, scope.row)"
            >
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-if="totalCount"
          v-model:currentPage="query.currentPage"
          v-model:page-size="query.pageSize"
          layout="prev, pager, next, jumper"
          :total="totalCount"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="centerDialogVisible"
      title="景点编辑"
      width="35%"
      :before-close="cancel"
    >
      <div>
        <el-scrollbar height="50vh">
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="100px"
            status-icon
          >
            <el-form-item label="景点logo" prop="logo">
              <!-- <img :src="`${IMG_URL}${ruleForm.logo}`" width="80" height="80" /> -->
              <el-upload
                action="#"
                list-type="picture-card"
                :auto-upload="false"
                :on-remove="handledel"
                :on-change="changeUploadImg"
                ref="upload"
                :file-list="fileList"
                :multiple="true"
                v-model="fileList"
                :limit="1"
                :class="{ hidden: fileList.length == 1 }"
              >
                <el-icon>
                  <Plus />
                </el-icon>
                <template #file="{ file }">
                  <div>
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url"
                      alt=""
                    />
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-preview"
                        @click="handlePictureCardPreview(file)"
                      >
                        <el-icon>
                          <ZoomIn />
                        </el-icon>
                      </span>
                      <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="handledel(file)"
                      >
                        <el-icon>
                          <Delete />
                        </el-icon>
                      </span>
                    </span>
                  </div>
                </template>
                <template #tip>
                  <div class="el-upload__tip">
                    只能上传 .jpg 或 .png 格式图片，且图片大小不能超过256KB！
                  </div>
                </template>
              </el-upload>
              <!-- 放大的图片 -->
              <el-dialog v-model="dialogVisible" top="7vh">
                <img
                  w-full
                  :src="dialogImageUrl"
                  alt="Preview Image"
                  style="width: 100%; height: auto"
                />
              </el-dialog>
            </el-form-item>
            <el-form-item label="景点名" prop="name">
              <el-input v-model="ruleForm.name" @input="checkName" />
            </el-form-item>

            <el-form-item label="景点级别" prop="category">
              <el-radio-group v-model="ruleForm.category">
                <el-radio :label="4">1A</el-radio>
                <el-radio :label="3">2A</el-radio>
                <el-radio :label="2">3A</el-radio>
                <el-radio :label="1">4A</el-radio>
                <el-radio :label="0">5A</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="简介内容" prop="desc">
              <el-input v-model="ruleForm.desc" />
            </el-form-item>
            <el-form-item label="详细内容" prop="content">
              <el-input v-model="ruleForm.content" type="textarea"/>
            </el-form-item>
          </el-form>
        </el-scrollbar>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >更新</el-button
          >
          <el-button @click="cancel">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { useRouter, useRoute } from "vue-router";
import { ref, reactive, watch } from "vue";
import request from "../../utils/request";
import { ElNotification, ElMessage } from "element-plus";
import { EditPen, Search } from "@element-plus/icons-vue";
// import moment from "moment";
import { IMG_URL } from "@/utils/imgStatic";

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const disabled = ref(false);
const fileList = ref([]);
const upload = ref(null);

// 移除图片
const handledel = (file) => {
  fileList.value = [];
};
//展示大图
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

//限制大小
//文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const changeUploadImg = (file) => {
  const isJPG = file.raw.type === "image/jpeg";
  const isPNG = file.raw.type === "image/png";
  if (!isJPG && !isPNG) {
    ElMessage.error("上传图片只能是 JPG 或者 PNG 格式！");
    // 取消时在文件列表中删除该文件
    upload.value.handleRemove(file);
    return isJPG || isPNG;
  } else if (file.size / 5120 > 1024) {
    // ElMessage.error("图片大小不能超过256KB！");
    ElMessage.error("图片过大！");
    upload.value.handleRemove(file);
    return false;
  } else {
    fileList.value.push(file);
    rules.logo = [];
  }
};

let breadList = []; // 路由集合
const route = useRoute();
const getBreadcrumb = (url) => {
  let matched = url.matched;
  //如果不是首页
  if ("Home" == matched[0].name) {
    matched[0].meta = { title: "系统首页" };
  }
  breadList = matched;
};
watch(
  route,
  (newValue, oldValue) => {
    // console.log(222222,newValue)
    getBreadcrumb(newValue);
  },
  { deep: true, immediate: true }
);


//取消表单
const cancel = () => {
  centerDialogVisible.value = false;
  fileList.value = [];
};

const ruleForm = reactive({
  travelId: "",
  name: "",
  desc: "",
  category: 0,
  content: "",
  logo: "",
});
const rules = reactive({
  name: [
    {
      required: true,
      message: "请输入景点名",
      trigger: ["blur", "change"],
    },
    {
      pattern: /^\S*$/, // 正则表达式校验用户名，不允许空格
      message: "景点名中不能有空格",
      trigger: ["blur", "change"],
    },
    // {
    //   pattern: /^[a-zA-Z0-9_]+$/, // 正则表达式校验用户名，只允许字母、数字和下划线
    //   message: "用户名只能包含字母、数字和下划线",
    //   trigger: ["blur", "change"],
    // },
  ],
  desc: [
    {
      required: false,
      message: "请输入景点介绍",
      trigger: "blur",
    },
  ],
  category: [
    {
      required: true,
      message: "请选择景点类型",
      trigger: "change",
    },
  ],
  content: [
    {
      required: false,
      message: "请输入景点内容",
      trigger: "change",
    },
  ],
  logo: [
    {
      required: false,
      message: "请上传景点图片",
      trigger: "change",
    },
  ],
});
const ruleFormRef = ref();
const centerDialogVisible = ref(false);
const query = reactive({
  category: "",
  name: "",
  currentPage: 1,
  pageSize: 5,
});
const tableData = ref([]);
const totalCount = ref(0);
// 获取表格数据
const getData = () => {
  request
    .request({
      url: "/travel/getAllTravelByPage",
      params: {
        category: query.category,
        name: query.name,
        currentPage: query.currentPage,
        pageSize: query.pageSize,
      },
      method: "get",
    })
    .then((res) => {
      //获取当前页的数据
      tableData.value = res.data.data.rows;
      //获取总记录数
      totalCount.value = res.data.data.count;
    })
    .catch((e) => {
      console.log(e);
    });
};

getData();
// 查询操作
const handleSearch = () => {
  query.currentPage = 1;
  getData();
};
// 分页导航
const handleCurrentChange = (val) => {
  query.currentPage = val;
  getData();
  // console.log(val);
};
// 删除操作
const handleDelete = (index, row) => {
  request
    .request({
      url: "/travel/handleDelete",
      method: "post",
      data: {
        travelId: row.travelId,
      },
    })
    .then((res) => {
      // 在成功回调中可以根据后端返回的数据进行相应处理
      if (res.data.code == "200" && res.data.msg == "删除成功") {
        ElMessage({
          message: res.data.msg,
          type: "success",
        });
        // fetchData();
        getData();
      } else if (res.data.code == "201" || res.data.code == "500") {
        ElMessage({
          message: res.data.msg,
          type: "error",
        });
      }
    })
    .catch((e) => {
      console.log(e);
    });
};

const handleEdit = (index, row) => {
  centerDialogVisible.value = true;
  ruleForm.travelId = row.travelId; // 添加用户ID
  ruleForm.name = row.name;
  ruleForm.desc = row.desc;
  ruleForm.category = row.category;
  ruleForm.content = row.content;
  ruleForm.logo = row.logo;
  fileList.value = [{
      name:ruleForm.logo,
      url:`${IMG_URL}${ruleForm.logo}`
    
  }]//充值图片
};

//时间格式YY--MM--HH
const formatDate = (row, column) => {
  const date = new Date(row.updatedAt);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}`;
};

//提交表单
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    const formData = new FormData();
    fileList.value.forEach((value, index) => {
      formData.append("imgfile", value.raw);
    });
    formData.append("travelId", ruleForm.travelId);
    formData.append("name", ruleForm.name);
    formData.append("desc", ruleForm.desc);
    formData.append("category", ruleForm.category);
    formData.append("content", ruleForm.content);
    if (valid) {
      request
        .post("/travel/updateTravel", formData, {
          headers: {
            "Content-Type":
              "multipart/form-data;charset=UTF-8; boundary=<calculated when request is sent>",
          },
        })
        .then(() => {
          ElNotification({
            title: "提示",
            message: "景点信息修改成功",
            type: "success",
          });
          // 关闭修改窗口
          centerDialogVisible.value = false;
          getData();
        });
    } else {
      ElNotification({
        title: "校验失败",
        message: "请重新填写信息",
        type: "error",
      });
    }
  });
};
const checkname = async () => {};
</script>

<style>
.hidden .el-upload--picture-card {
  display: none;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 200px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
